module ecs {
    export class Entity implements IComparable<Entity> {
        private static _idGenerator: number;
        public _updateOrder: number = 0;
        /** 该实体所属的场景 */
        public Scene: Scene;

        public readonly Id: number;
        public readonly Transform: Transform;
        public readonly Components:ComponentList;

        public Name: string;
        public componentBits: BitSet;
        /** 指定应多久调用一次此实体更新方法。 1表示每帧，2表示其他，依此类推 */
        public UpdateInterval = 1;

        private _tag: number = 0;
        /** 以后可用于在场景中查询具有特定标签的所有实体 */
        public get Tag(): number{
            return this._tag;
        }
        public set Tag(value: number){
            this.SetTag(value);
        }

        private _enabled: boolean = true;
        public get Enabled(): boolean{
            return this._enabled;
        }

        public set Enabled(value: boolean){
            this.SetEnabled(value);
        }

        constructor(name: string) {
            this.Components = new ComponentList(this);
            this.Transform = new Transform(this);
            this.Name = name;
            this.Id = Entity._idGenerator++;

            if (Core.entitySystemsEnabled){
                this.componentBits = new BitSet();
            }
        }

        /** 设置实体的标签 */
        public SetTag(tag: number): Entity{
            if (this._tag != tag){
                if (this.Scene != null){
                    this.Scene.Entities.RemoveFromTagList(this);
                }
                this._tag = tag;
                if (this.Scene != null){
                    this.Scene.Entities.AddToTagList(this);
                }
            }

            return this;
        }

        public SetEnabled(isEnabled: boolean): Entity{
            if (this._enabled != isEnabled){
                this._enabled = isEnabled;

                if (this._enabled){
                    this.Components.OnEntityEnabled();
                }else{
                    this.Components.OnEntityDisabled();
                }
            }

            return this;
        }

        /** 将组件添加到组件列表。 返回组件。 */
        public AddComponent<T extends Component>(component: T): T{
            component.Entity = this;
            this.Components.Add(component);
            component.Initialize();

            return component;
        }

        /** 只要启用了实体，就会调用每帧 */
        public Update(){
            this.Components.Update();
        }

        public OnTransformChanged(comp: transform.Component){
            this.Components.OnEntityTransformChanged(comp);
        }

        public CompareTo(other: Entity): number {
            var compare = this._updateOrder.CompareTo(other._updateOrder);
            if (compare == 0)
                compare = this.Id.CompareTo(other.Id);
            return compare;
        }
    }
}